//
//  CYUserAccount.swift
//  CYSinaWB
//
//  Created by mac on 16/2/20.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class CYUserAccount: NSObject,NSCoding {
    //用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    
    //	access_token的生命周期，单位是秒数。
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //过期时间
    var expires_date: NSDate?
    
    //当前授权用户的UID。
    var uid: String?
    
//    用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    //友好显示名称
    var name: String?
    
    //KVC设置部分的值
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    //过滤没有使用的数据
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {   }
    
    //重写description
    override var description: String {
        let keys = ["access_token","expires_in","uid","avatar_large","name","expires_date"]
        let dict = self.dictionaryWithValuesForKeys(keys)
        return dict.description
    }
    
    //模型数据的存储和读取(沙盒)
    func saveAccount() {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
        print(path)
        
        //调用归档
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
    }
    class func loadUserInfo() ->CYUserAccount? {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? CYUserAccount {
            //判断用户token是否过期
            if userAccount.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            return userAccount
            }
        }
        return nil
    }
    //NSCoding协议   归档解归档
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        
    }
}
